﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using EasierRdp.Base;
using EasierRdp.Util;

namespace EasierRdp.Models
{
    class RdpUserRef : RdpRef
    {
        public const string ElementName = "UserRef";

        protected override RdpModel GetRefObject(int id)
        {
            return RdpContext.Users[id];
        }

        public override XElement ToXml()
        {
            return new XElement(ElementName,
                new XAttribute(AttributeDefault, Default),
                new XAttribute(AttributeId, Id));
        }

        public RdpUserRef(int id)
        {
            Id = id;
        }

        public RdpUserRef(XElement element)
        {
            if (element != null)
            {
                Default = element.GetBoolean(AttributeDefault);
                Id = element.GetInt(AttributeId);
                return;
            }
            throw new ArgumentNullException("element");
        }
    }

    static class RdpUserRefExtension
    {
        public static IEnumerable<XElement> ToXml(this IEnumerable<RdpUserRef> src)
        {
            return src == null ? null : src.Select(s => s.ToXml());
        }

        public static void FromXml(this IList<RdpUserRef> src, XElement parentElement, string elementName)
        {
            foreach (var item in parentElement.Elements(elementName).Select(e => new RdpUserRef(e)))
            {
                src.Add(item);
            }
        }
    }
}
